'use strict';

const {
	log
} = require("console");

module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/files_mzgl/dy_tv_series/kh/gitList2 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			istoken,
			update_witch,
			album_id,
			updata,
			back
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		//获取后台生成抖音剧集
		let dbName = "dy_tv"; // 表名
		let odata = await vk.baseDao.select({
			dbName: dbName, // 表名
			getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
			getMain: false,
			pageSize: 200,
			whereJson: { // 条件
				album_id: album_id,
			},
			// 按_id降序 asc 升序 desc 降序 
			sortArr: [{
				name: "seq",
				type: "asc"
			}],
		});
		// res.data = odata.rows[0]
		console.log("看看当前剧数据", odata.rows[0]);

		let appid = odata.rows[0].ma_app_id
		let tv_id = odata.rows[0]._id
		// 获取分集数据
		let data2 = await vk.baseDao.select({
			dbName: "dy_tv_series", // 表名
			getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
			getMain: false,
			pageSize: 200,
			whereJson: { // 条件
				tv_id: tv_id,
			},
			// 按_id降序 asc 升序 desc 降序 
			sortArr: [{
				name: "seq",
				type: "asc"
			}],
		});
		let temp_series_list = [] //预览数据
		//切换源
		if (back) {
			let nowtime = new Date().getTime()
			let endtime = (data2.rows[0].back_url_expire - 3600) * 1000
			if (nowtime < endtime) {
				data2.rows.map((item) => {
					temp_series_list[item.seq - 1] = {
						link: item.back_up_play_url,
						serie: item.seq
					}
				})
				res.temp_series_list = temp_series_list
				return res
			}
		}
		let nowtime = new Date().getTime()
		let endtime = (data2.rows[0].main_url_expire - 3600) * 1000
		if (nowtime < endtime && !updata) {
			data2.rows.map((item) => {
				temp_series_list[item.seq - 1] = {
					link: item.url,
					serie: item.seq
				}
			})
			res.temp_series_list = temp_series_list
			return res
		}



		//获取accessToken
		// 判断是否已经获取到token
		let access_token = ''
		if (!istoken) {
			let appdata = await db.collection("a_appid").where({
				appid: appid,
			}).get()
			let appsecret = appdata.data[0].appsecret
			let urlA = "https://open.douyin.com/oauth/client_token/"
			const accessToken = await uniCloud.httpclient.request(urlA, {
				method: 'POST',
				headers: {
					"Content-Type": "application/json",
				},
				data: {
					client_key: appid, // id
					client_secret: appsecret, // 密钥
					grant_type: "client_credential",
				},
				dataType: 'json', // 指定返回值为json格式，自动进行parseK
			})

			access_token = accessToken.data.data.access_token
			res.access_token = access_token
			console.log("看看token", access_token);
		} else {
			access_token = istoken
		}
		let urlT = "https://open.douyin.com/api/dyc_voc/get_video_by_vid"
		async function getVideoUrl(vid) {
			let resA = await uniCloud.httpclient.request(urlT, {
				method: 'POST',
				headers: {
					"Content-Type": "application/json",
					"access-token": access_token,
				},
				data: {
					vid: vid,
					expire_time: 14 * 24 * 3600
				},
				dataType: 'json', // 指定返回值为json格式，自动进行parseK
			})
			console.log('看看返回的数据', resA);

			return resA.res.data.data
		}

		// 分集获取视频信息
		await Promise.all(
			data2.rows.map(async (item) => {
				let urldata = await getVideoUrl(item.dy_cloud_id)
				await vk.baseDao.updateById({
					dbName: "dy_tv_series",
					id: item._id,
					dataJson: {
						back_url_expire: urldata[1].main_url_expire,
						back_up_play_url: urldata[1].main_play_url,
						url: urldata[0].main_play_url,
						main_url_expire: urldata[0].main_url_expire
					},
				});
				temp_series_list[item.seq - 1] = {
					link: urldata.main_play_url,
					serie: item.seq
				}
			})
		);

		res.temp_series_list = temp_series_list







		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}